package com.example.weight.greenSeasons.flocculation;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.SolidLiquid.shebeijiancha7_4jiancharen;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class xuningshebeijianchaChecker extends AppCompatActivity {
    private String username, factory;
    private ExpandableLayout expand_1;
    private ExpandableLayout expand_2;
    private Button textView1;
    private Button textView2;
    private TextView dateEdit;
    private TitleBar titleBar;
    private String id1="-100",id2="-100",id3="-100",id4="-100",id5="-100",id6="-100",id7="-100",id8="-100",id9="-100",id10="-100";
    private String remark1="-100",remark2="-100",remark3="-100",remark4="-100",remark5="-100",remark6="-100",remark7="-100",remark8="-100",remark9="-100",remark10="-100";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        username = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xuningshebeijiancha_checker);
        expand_1=findViewById(R.id.expandable_1);
        expand_2=findViewById(R.id.expandable_2);
//        textView1=findViewById(R.id.button_1);
        textView2=findViewById(R.id.button_2);

        dateEdit=findViewById(R.id.compost_editDate);
        Calendar calendar=Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH)+1; //第一个月从0开始，所以得到月份＋1
        Integer day = calendar.get(calendar.DAY_OF_MONTH);
        Integer hour24 = calendar.get(calendar.HOUR_OF_DAY);
        Integer minute = calendar.get(calendar.MINUTE);
        dateEdit.setText(year+"-"+month+"-"+day);

        CheckBox checkBox1 = findViewById(R.id.checkBox1);
        CheckBox checkBox2 = findViewById(R.id.checkBox2);
//        CheckBox checkBox3 = findViewById(R.id.checkBox3);
//        CheckBox checkBox4 = findViewById(R.id.checkBox4);
//        CheckBox checkBox5 = findViewById(R.id.checkBox5);
        CheckBox checkBox6 = findViewById(R.id.checkBox6);
        CheckBox checkBox7 = findViewById(R.id.checkBox7);
        CheckBox checkBox8 = findViewById(R.id.checkBox8);
        CheckBox checkBox9 = findViewById(R.id.checkBox9);
        CheckBox checkBox10 = findViewById(R.id.checkBox10);

        TextView textview1 = findViewById(R.id.equipment1_state);
        TextView textview2 = findViewById(R.id.equipment2_state);
//        TextView textview3 = findViewById(R.id.equipment3_state);
//        TextView textview4 = findViewById(R.id.equipment4_state);
//        TextView textview5 = findViewById(R.id.equipment5_state);
        TextView textview6 = findViewById(R.id.equipment6_state);
        TextView textview7 = findViewById(R.id.equipment7_state);
        TextView textview8 = findViewById(R.id.equipment8_state);
        TextView textview9 = findViewById(R.id.equipment9_state);
        TextView textview10 = findViewById(R.id.equipment10_state);

        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                if (checkBox1.isChecked() == false) {
                    allDone("大调节池液位计");
                }else if (checkBox2.isChecked() == false) {
                    allDone("大调节池搅拌器");
                }/*else if (checkBox3.isChecked() == false) {
                    allDone("过滤器");
                }else if (checkBox4.isChecked() == false) {
                    allDone("水洗喷嘴");
                }else if (checkBox5.isChecked() == false) {
                    allDone("喷淋滤嘴");
                }*/else if (checkBox6.isChecked() == false) {
                    allDone("使用液药箱探头");
                }else if (checkBox7.isChecked() == false) {
                    allDone("粉剂螺旋");
                }else if (checkBox8.isChecked() == false) {
                    allDone("1# 搅拌器");
                }else if (checkBox9.isChecked() == false) {
                    allDone("2# 搅拌器");
                }else if (checkBox10.isChecked() == false) {
                    allDone("上水系统");
                }else {
                    xuningshebeijianchaChecker.this.finish();
                }
            }
            @Override
            public void onTitleClick(View v) { }
            @Override
            public void onRightClick(View v) { }
        });
//        TextView text = findViewById(R.id.equipment1_state);
//        text.setTextColor(0x018786);
//        text.setText("正常");
        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/flocculationProduceCheck/findEquipList" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Log.d("jy", response);
                            JSONArray data;
                            if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")) {
                                data = jsonObject.getJSONArray("data");
                                if(data.length()>0){
                                    for(int i=0;i<data.length();i++){
                                        // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                                        JSONObject record = data.getJSONObject(i);
                                        // 得到 每个对象中的属性值
                                        if (record.get("equipmentName").equals(checkBox1.getText().toString())){
                                            if(!record.get("inspector").toString().equals("null")){
                                                checkBox1.setChecked(true);
                                                checkBox1.setEnabled(false);
                                            }
                                            id1 = record.get("id").toString();
                                            if(record.get("isNormal").equals("正常")){
                                                TextView text = findViewById(R.id.equipment1_state);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            }else {
                                                TextView text = findViewById(R.id.equipment1_state);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        }else if (record.get("equipmentName").equals(checkBox2.getText().toString())){
                                            if(!record.get("inspector").toString().equals("null")){
                                                checkBox2.setChecked(true);
                                                checkBox2.setEnabled(false);
                                            }
                                            id2 = record.get("id").toString();
                                            if(record.get("isNormal").equals("正常")){
                                                TextView text = findViewById(R.id.equipment2_state);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            }else {
                                                TextView text = findViewById(R.id.equipment2_state);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        }/*else if (record.get("equipmentName").equals(checkBox3.getText().toString())){
                                            if(!record.get("inspector").toString().equals("null")){
                                                checkBox3.setChecked(true);
                                                checkBox3.setEnabled(false);
                                            }
                                            id3 = record.get("id").toString();
                                            if(record.get("isNormal").equals("正常")){
                                                TextView text = findViewById(R.id.equipment3_state);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            }else {
                                                TextView text = findViewById(R.id.equipment3_state);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        }else if (record.get("equipmentName").equals(checkBox4.getText().toString())){
                                            if(!record.get("inspector").toString().equals("null")){
                                                checkBox4.setChecked(true);
                                                checkBox4.setEnabled(false);
                                            }
                                            id4 = record.get("id").toString();
                                            if(record.get("isNormal").equals("正常")){
                                                TextView text = findViewById(R.id.equipment4_state);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            }else {
                                                TextView text = findViewById(R.id.equipment4_state);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        }else if (record.get("equipmentName").equals(checkBox5.getText().toString())){
                                            if(!record.get("inspector").toString().equals("null")){
                                                checkBox5.setChecked(true);
                                                checkBox5.setEnabled(false);
                                            }
                                            id5 = record.get("id").toString();
                                            if(record.get("isNormal").equals("正常")){
                                                TextView text = findViewById(R.id.equipment5_state);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            }else {
                                                TextView text = findViewById(R.id.equipment5_state);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        }*/else if (record.get("equipmentName").equals(checkBox6.getText().toString())){
                                            if(!record.get("inspector").toString().equals("null")){
                                                checkBox6.setChecked(true);
                                                checkBox6.setEnabled(false);
                                            }
                                            id6 = record.get("id").toString();
                                            if(record.get("isNormal").equals("正常")){
                                                TextView text = findViewById(R.id.equipment6_state);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            }else {
                                                TextView text = findViewById(R.id.equipment6_state);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        }else if (record.get("equipmentName").equals(checkBox7.getText().toString())){
                                            if(!record.get("inspector").toString().equals("null")){
                                                checkBox7.setChecked(true);
                                                checkBox7.setEnabled(false);
                                            }
                                            id7 = record.get("id").toString();
                                            if(record.get("isNormal").equals("正常")){
                                                TextView text = findViewById(R.id.equipment7_state);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            }else {
                                                TextView text = findViewById(R.id.equipment7_state);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        }else if (record.get("equipmentName").equals(checkBox8.getText().toString())){
                                            if(!record.get("inspector").toString().equals("null")){
                                                checkBox8.setChecked(true);
                                                checkBox8.setEnabled(false);
                                            }
                                            id8 = record.get("id").toString();
                                            if(record.get("isNormal").equals("正常")){
                                                TextView text = findViewById(R.id.equipment8_state);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            }else {
                                                TextView text = findViewById(R.id.equipment8_state);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        }else if (record.get("equipmentName").equals(checkBox9.getText().toString())){
                                            if(!record.get("inspector").toString().equals("null")){
                                                checkBox9.setChecked(true);
                                                checkBox9.setEnabled(false);
                                            }
                                            id9 = record.get("id").toString();
                                            if(record.get("isNormal").equals("正常")){
                                                TextView text = findViewById(R.id.equipment9_state);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            }else {
                                                TextView text = findViewById(R.id.equipment9_state);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        }else if (record.get("equipmentName").equals(checkBox10.getText().toString())){
                                            if(!record.get("inspector").toString().equals("null")){
                                                checkBox10.setChecked(true);
                                                checkBox10.setEnabled(false);
                                            }
                                            id10 = record.get("id").toString();
                                            if(record.get("isNormal").equals("正常")){
                                                TextView text = findViewById(R.id.equipment10_state);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            }else {
                                                TextView text = findViewById(R.id.equipment10_state);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        }
                                    }
                                }
                            }
                            checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if(isChecked){
                                        checkEquipment(checkBox1,textview1,id1);
                                    }
                                }
                            });
                            checkBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if(isChecked) {
                                        checkEquipment(checkBox2,textview2,id2);
                                    }
                                }

                            });
                            /*
                            checkBox3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){

                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if(isChecked) {
                                        checkEquipment(checkBox3,textview3,id3);
                                    }
                                }

                            });
                            checkBox4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if(isChecked) {
                                        checkEquipment(checkBox4,textview4,id4);
                                    }
                                }

                            });
                            checkBox5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if(isChecked) {
                                        checkEquipment(checkBox5,textview5,id5);
                                    }
                                }
                            });
                             */
                            checkBox6.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if(isChecked) {
                                        checkEquipment(checkBox6,textview6,id6);
                                    }
                                }
                            });
                            checkBox7.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if(isChecked) {
                                        checkEquipment(checkBox7,textview7,id7);
                                    }
                                }
                            });
                            checkBox8.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if(isChecked){
                                        checkEquipment(checkBox8,textview8,id8);
                                    }
                                }
                            });
                            checkBox9.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if(isChecked) {
                                        checkEquipment(checkBox9,textview9,id9);
                                    }
                                }
                            });
                            checkBox10.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if(isChecked) {
                                        checkEquipment(checkBox10,textview10,id10);
                                    }
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(xuningshebeijianchaChecker.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    public void show1(View view) {
        if (expand_1.isExpanded()){
            textView1.setText("+ 除臭系统");
        }else{
            textView1.setText("- 除臭系统");
        }

        expand_1.toggle();
    }
    public void show2(View view) {
        if (expand_2.isExpanded()){
            textView2.setText("+ 药剂装置");
        }else{
            textView2.setText("- 药剂装置");
        }

        expand_2.toggle();
    }

    public void checkEquipment(CheckBox equipment_name,TextView operatorRemark, String id) {
        final EditText equipment_problem = new EditText(this);
        equipment_problem.setHint("   输入问题:");
        new AlertDialog.Builder(this)
                //.setTitle(" “"+ equipment_name.getText().toString() +"” 已检查")
                .setTitle("操作人结论是否正确？如果有误请在下方填写问题")
                .setView(equipment_problem)
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->{
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                    equipment_name.setChecked(false);
                }
                ))
                .setPositiveButton("提交", (dialog, which) ->{
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/flocculationProduceCheck/addExaminationalForm";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.equals("200")){
                                            Toast.makeText(xuningshebeijianchaChecker.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                            equipment_name.setEnabled(false);
                                        }
                                        else
                                            Toast.makeText(xuningshebeijianchaChecker.this,
                                                    "1保存失败", Toast.LENGTH_SHORT).show();

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(xuningshebeijianchaChecker.this,
                                    "2保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", id);   ///------------------------这里要id
                            map.put("remarks", operatorRemark.getText().toString()+"_"+equipment_problem.getText().toString());
                            map.put("inspector", username);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void allDone(String equipment_name){
        new AlertDialog.Builder(this)
                .setTitle(" “"+ equipment_name +"” 未检查，是否退出")
                .setCancelable(false)
                .setNegativeButton("否", ((dialog, which) -> {
                    return;
                }))
                .setPositiveButton("是", (dialog, which) ->{
                    xuningshebeijianchaChecker.this.finish();
                })
                .show();
    }
}